import Vue from "vue";
import Router from "vue-router";
import Login from "@/views/common/login";
import Reset from "@/views/common/reset";
import ErrorPage from "@/views/common/error-404";
import {
	createRouter,
	createWebHistory
} from "vue-router"
// 导入 /src/store/index.js
import store from "@/store/index";

// Vue.use(Router);

const staticRoutes = [{
	path: "/",
	name: "Login",
	component: Login
}, {
	path: "/reset/:token/:email([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})",
	name: "Reset",
	component: Reset,
}, {
	path: "/common/error",
	name: "ErrorPage",
	component: ErrorPage
}];

const router = createRouter({
	history: createWebHistory(),
	routes: staticRoutes
});


router.beforeEach(async (to, from, next) => {
	const token = sessionStorage.getItem("token");
	// 判断是否访问重置密码页面
	if (to.path.match(/^\/reset\/[^\/]+\/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/)) {
		// 如果已经是Reset组件，则直接放行
		const [, email] = to.path.match(/^\/reset\/[^\/]+\/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/)
		sessionStorage.setItem("email", to.params.email)
		sessionStorage.setItem("R-TOKEN", to.params.token)
		// console.log(sessionStorage.getItem('visited'))
		if (to.name === "Reset" && !sessionStorage.getItem('visited')) {
			sessionStorage.setItem('visited', true);
			next();
			return;
		}
		if (sessionStorage.getItem('visited')) {
			// 否则重定向到Reset组件
			alert("禁止重复访问！");
			next({
				name: "Login",
			});
		}
		return;
	}
	//此处应该判断token是否过期？
	token == null ? false : true;
	if (!token) {
		if (to.name != "Login") {
			alert("[401]:您还没有登录!");
			next({
				name: "Login"
			});
			return;
		}
	} else {
		let hasRoute = store.state.hasRoute;
		// console.log("[ROUTER]有 Token, hasGetRouter: " + hasRoute);
		if (!store.state.hasRoute) {
			// 暂无 Route 数据(去 store 中获取)
			await store.dispatch("ACTION_GET_MENU");
			next({
				...to,
				replace: true
			});
			return;
		}
	}
	var existFlag = false
	router.getRoutes().forEach(item => {
		if (to.fullPath.includes(item.path)) {
			existFlag = true
			return
		}
	})
	if (!existFlag) {
		console.log("-------------不存在此路径-------------")
		// console.log(to.fullPath)
		next({
			name: 'ErrorPage'
		})
	}
	next();
});

export default router;
